package com.jhgsys.internal.contractor.controller;

import com.jhgsys.internal.common.annotation.Log;
import com.jhgsys.internal.common.controller.BaseController;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.entity.FebsResponse;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.contractor.entity.BaseContractor;
import com.jhgsys.internal.contractor.service.IBaseContractorService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.Map;

/**
 * 承包方设置 Controller
 *
 * @author admin
 * @date 2024-07-29 14:19:02
 */
@Slf4j
@Validated
@Controller
public class BaseContractorController extends BaseController {

    @Autowired
    private IBaseContractorService baseContractorService;

    @GetMapping(FebsConstant.VIEW_PREFIX + "baseContractor")
    @RequiresPermissions("baseContractor:view")
    public String baseContractorIndex(Model model){
        model.addAttribute("tenantList", getTenantList());
        model.addAttribute("tenantId", getCurrentTenantId());
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        return FebsUtil.view("contractor/baseContractor/baseContractorList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "baseContractor/add")
    @RequiresPermissions("baseContractor:view")
    public String baseContractorAdd(Model model){
        model.addAttribute("tenantList", getTenantList());
        model.addAttribute("tenantId", getCurrentTenantId());
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        return FebsUtil.view("contractor/baseContractor/baseContractorEdit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "baseContractor/update/{contractorId}")
    @RequiresPermissions("baseContractor:view")
    public String baseContractorUpdate(Model model, @PathVariable("contractorId") String contractorId){
        model.addAttribute("tenantList", getTenantList());

        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        BaseContractor contractor = baseContractorService.findBaseContractorById(contractorId);
        model.addAttribute("baseContractor", contractor);
        model.addAttribute("tenantId", contractor.getTenantId());
        return FebsUtil.view("contractor/baseContractor/baseContractorEdit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "baseContractor/detail/{contractorId}")
    @RequiresPermissions("baseContractor:view")
    public String baseContractorDetail(Model model, @PathVariable("contractorId") String contractorId){


        BaseContractor contractor = baseContractorService.findBaseContractorById(contractorId);
        model.addAttribute("baseContractor", contractor);
        return FebsUtil.view("contractor/baseContractor/baseContractorDetail");
    }

    /**
     * 查询（所有）
     * @author admin
     * @date 2024-07-29 14:19:02
     */
    @GetMapping("baseContractor")
    @ResponseBody
    @RequiresPermissions("baseContractor:view")
    public FebsResponse getAllBaseContractors(BaseContractor baseContractor) {
        return new FebsResponse().success().data(baseContractorService.findBaseContractors(baseContractor));
    }

    /**
     * 查询（分页）
     * @author admin
     * @date 2024-07-29 14:19:02
     */
    @GetMapping("baseContractor/list")
    @ResponseBody
    @RequiresPermissions("baseContractor:view")
    public FebsResponse baseContractorList(QueryRequest request, BaseContractor baseContractor) {
        Map<String, Object> dataTable = getDataTable(this.baseContractorService.findBaseContractors(request, baseContractor));
        return new FebsResponse().success().data(dataTable);
    }

    /**
     * 新增 BaseContractor
     * @author admin
     * @date 2024-07-29 14:19:02
     */
    @Log("新增BaseContractor")
    @PostMapping("baseContractor")
    @ResponseBody
    @RequiresPermissions("baseContractor:view")
    public FebsResponse addBaseContractor(BaseContractor baseContractor) throws FebsException {
        try {
            if(StringUtils.isBlank(baseContractor.getContractorCode())){
                return new FebsResponse().fail().message("承包商编号不能为空！");
            }
            if(StringUtils.isBlank(baseContractor.getContractorName())){
                return new FebsResponse().fail().message("承包商名称不能为空！");
            }
            if(StringUtils.isBlank(baseContractor.getContacts())){
                return new FebsResponse().fail().message("联系人不能为空！");
            }
            if(StringUtils.isBlank(baseContractor.getContactsPhone())){
                return new FebsResponse().fail().message("联系方式不能为空！");
            }
            if(StringUtils.isBlank(baseContractor.getTenantId())){
                if(hasHeadCompanyRole()){
                    return new FebsResponse().fail().message("所属公司不能为空！");
                }else {
                    baseContractor.setTenantId(getCurrentTenantId());
                }

            }

            BaseContractor queryContractor = this.baseContractorService.findByName(baseContractor.getContractorName());
            if(!ObjectUtils.isEmpty(queryContractor)){
                return new FebsResponse().fail().message("承包商名称已存在！");
            }
            baseContractor.setCreatedBy(getCurrentUser().getUserName());
            this.baseContractorService.createBaseContractor(baseContractor);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "新增BaseContractor失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 逻辑删除 BaseContractor
     * @author admin
     * @date 2024-07-29 14:19:02
     */
    @Log("逻辑删除BaseContractor")
    @GetMapping("baseContractor/delete/{id}")
    @ResponseBody
    @RequiresPermissions("baseContractor:view")
    public FebsResponse deleteBaseContractor(@PathVariable("id") String baseContractorIds) throws FebsException {
        try {
            BaseContractor baseContractor = new BaseContractor();
            baseContractor.setContractorId(baseContractorIds);
            baseContractor.setDeletedBy(getCurrentUser().getUserName());
            baseContractor.setDeletedTime(new Date());
            baseContractor.setDeletedFlg(FebsConstant.INVALID);
            this.baseContractorService.updateBaseContractorDeletedFlg(baseContractor);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "删除BaseContractor失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }



    /**
     * 修改 BaseContractor
     * @author admin
     * @date 2024-07-29 14:19:02
     */
    @Log("修改BaseContractor")
    @PostMapping("baseContractor/update")
    @ResponseBody
    @RequiresPermissions("baseContractor:view")
    public FebsResponse updateBaseContractor(BaseContractor baseContractor) throws FebsException {
        try {
            if(StringUtils.isBlank(baseContractor.getContractorId())){
                return new FebsResponse().fail().message("承包商Id不能为空！");
            }
            if(StringUtils.isBlank(baseContractor.getContractorCode())){
                return new FebsResponse().fail().message("承包商编号不能为空！");
            }
            if(StringUtils.isBlank(baseContractor.getContractorName())){
                return new FebsResponse().fail().message("承包商名称不能为空！");
            }
            if(StringUtils.isBlank(baseContractor.getContacts())){
                return new FebsResponse().fail().message("联系人不能为空！");
            }
            if(StringUtils.isBlank(baseContractor.getContactsPhone())){
                return new FebsResponse().fail().message("联系方式不能为空！");
            }
            BaseContractor queryContractor = this.baseContractorService.findByName(baseContractor.getContractorName());
            if(!ObjectUtils.isEmpty(queryContractor) && !baseContractor.getContractorId().equals(queryContractor.getContractorId())){
                return new FebsResponse().fail().message("承包商名称已存在！");
            }

            baseContractor.setUpdatedBy(getCurrentUser().getUserName());
            this.baseContractorService.updateBaseContractor(baseContractor);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "修改BaseContractor失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 修改承包商状态
     * @param baseContractor
     * @return
     * @throws FebsException
     */
    @Log("修改承包商状态")
    @PostMapping("baseContractor/updateContractorStatus")
    @ResponseBody
    @RequiresPermissions(value={"baseContractor:update"},logical= Logical.OR)
    public FebsResponse updatePostStatus(BaseContractor baseContractor) throws FebsException {
        try {
            if(StringUtils.isBlank(baseContractor.getContractorId())){
                return new FebsResponse().fail().message("承包商Id不能为空！");
            }
            if(StringUtils.isBlank(baseContractor.getStatus())){
                return new FebsResponse().fail().message("承包商状态不能为空！");
            }
            baseContractor.setUpdatedBy(getCurrentUser().getUserName());
            baseContractor.setUpdatedTime(new Date());

            this.baseContractorService.updateById(baseContractor);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "修改承包商状态失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }



//    /**
//     * 导出 BaseContractor的excel
//     * @author admin
//     * @date 2024-07-29 14:19:02
//     */
//    @PostMapping("baseContractor/excel")
//    @ResponseBody
//    @RequiresPermissions("baseContractor:view")
//    public void export(QueryRequest queryRequest, BaseContractor baseContractor, HttpServletResponse response) throws FebsException {
//        try {
//            List<BaseContractor> baseContractors = this.baseContractorService.findBaseContractors(queryRequest, baseContractor).getRecords();
//            ExcelKit.$Export(BaseContractor.class, response).downXlsx(baseContractors, false);
//        } catch (Exception e) {
//            String message = "导出Excel失败";
//            log.error(message, e);
//            throw new FebsException(message);
//        }
//    }
}
